package com.gaofans.nrpc.common.processor;

import com.gaofans.nrpc.common.protocol.RpcResponse;
import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.Map;

/**
 * @author GaoFans
 */
public class RpcContext{

    private final ChannelHandlerContext ctx;
    private final static ThreadLocal<RpcContext> LOCAL = new ThreadLocal<>();
    private final Map<String,Object> data;
    private boolean isClear;
    private final long sequenceId;

    public RpcContext(ChannelHandlerContext ctx,long sequenceId) {
        this.ctx = ctx;
        this.data = new HashMap<>();
        this.isClear = false;
        this.sequenceId = sequenceId;
        LOCAL.set(this);
    }

    public static RpcContext current(){
        return LOCAL.get();
    }

    private void isClear(){
        if (this.isClear){
            throw new IllegalStateException("该对象已清空，请重新创建");
        }
    }

    public Object get(String key){
        isClear();
        return data.get(key);
    }

    public void set(String key,Object value){
        isClear();
        data.put(key,value);
    }

    public Object remove(String key){
        isClear();
        return data.remove(key);
    }

    public ChannelHandlerContext ctx(){
        isClear();
        return ctx;
    }

    public void writeErrorResponse(String error){
        RpcResponse response = new RpcResponse();
        response.setSuccess(false);
        response.setEnd(true);
        response.setError(error);
        response.setSequenceId(sequenceId);
        ctx.writeAndFlush(response);
    }

    /**
     * 清空
     */
    public void clear(){
        LOCAL.remove();
        data.clear();
        isClear = true;
    }
}
